using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Net.Http;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace WindowsFormsDataBaice
{
    public class UserManagementForm : Form
    {
        private TextBox txtUsername;
        private TextBox txtRealName;
        private TextBox txtPassword;
        private TextBox txtConfirmPassword;
        private RadioButton rbMale;
        private RadioButton rbFemale;
        private TextBox txtAddress;
        private TextBox txtContactPhone;
        private TextBox txtPinyinAbbreviation;
        private ComboBox cboType;
        private ComboBox cboDepartment;
        private TextBox txtRegistrationFee;
        private TextBox txtRemark;
        private Button btnSubmit;
        private Button btnReset;

        private readonly HttpClient httpClient;
        private readonly string apiBaseUrl;

        public UserManagementForm()
        {
            httpClient = new HttpClient();
            apiBaseUrl = ConfigurationManager.AppSettings["ApiBaseUrl"] ?? "http://101.201.170.32:5115";
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.Text = "员工添加";
            this.Size = new Size(650, 1000);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.BackColor = Color.White;

            // 创建主面板
            Panel mainPanel = new Panel
            {
                Dock = DockStyle.Fill,
                AutoScroll = true,
                Padding = new Padding(10)
            };

            // 标题
            Label lblTitle = new Label
            {
                Text = "员工信息添加",
                Font = new Font("微软雅黑", 12, FontStyle.Bold),
                ForeColor = Color.FromArgb(52, 73, 94),
                TextAlign = ContentAlignment.MiddleCenter,
                Dock = DockStyle.Top,
                Height = 20
            };

            // 创建表单面板 - 使用FlowLayoutPanel确保所有控件都能显示
            FlowLayoutPanel formPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Fill,
                AutoScroll = true,
                Padding = new Padding(10),
                FlowDirection = FlowDirection.TopDown,
                WrapContents = false
            };

            // 用户名 - 第一个字段，确保在最顶部
            Panel usernamePanel = new Panel { Width = 550, Height = 40 };
            Label lblUsername = new Label { Text = "用户名:", Font = new Font("微软雅黑", 9), Location = new Point(10, 10), Width = 80 };
            txtUsername = new TextBox { Font = new Font("微软雅黑", 9), Location = new Point(100, 8), Width = 200, Height = 25 };
            usernamePanel.Controls.Add(lblUsername);
            usernamePanel.Controls.Add(txtUsername);

            // 用户密码
            Panel passwordPanel = new Panel { Width = 550, Height = 40 };
            Label lblPassword = new Label { Text = "用户密码:", Font = new Font("微软雅黑", 9), Location = new Point(10, 10), Width = 80 };
            txtPassword = new TextBox { Font = new Font("微软雅黑", 9), Location = new Point(100, 8), Width = 200, Height = 25, UseSystemPasswordChar = true };
            passwordPanel.Controls.Add(lblPassword);
            passwordPanel.Controls.Add(txtPassword);

            // 确认密码
            Panel confirmPasswordPanel = new Panel { Width = 550, Height = 40 };
            Label lblConfirmPassword = new Label { Text = "确认密码:", Font = new Font("微软雅黑", 9), Location = new Point(10, 10), Width = 80 };
            txtConfirmPassword = new TextBox { Font = new Font("微软雅黑", 9), Location = new Point(100, 8), Width = 200, Height = 25, UseSystemPasswordChar = true };
            confirmPasswordPanel.Controls.Add(lblConfirmPassword);
            confirmPasswordPanel.Controls.Add(txtConfirmPassword);

            // 用户姓名
            Panel realNamePanel = new Panel { Width = 550, Height = 40 };
            Label lblRealName = new Label { Text = "用户姓名:", Font = new Font("微软雅黑", 9), Location = new Point(10, 10), Width = 80 };
            txtRealName = new TextBox { Font = new Font("微软雅黑", 9), Location = new Point(100, 8), Width = 200, Height = 25 };
            realNamePanel.Controls.Add(lblRealName);
            realNamePanel.Controls.Add(txtRealName);

            // 性别
            Panel genderPanel = new Panel { Width = 550, Height = 40 };
            Label lblGender = new Label { Text = "性别:", Font = new Font("微软雅黑", 9), Location = new Point(10, 10), Width = 80 };
            rbMale = new RadioButton { Text = "男", Font = new Font("微软雅黑", 9), Location = new Point(100, 8), Checked = true, AutoSize = true };
            rbFemale = new RadioButton { Text = "女", Font = new Font("微软雅黑", 9), Location = new Point(180, 8), AutoSize = true };
            genderPanel.Controls.Add(lblGender);
            genderPanel.Controls.Add(rbMale);
            genderPanel.Controls.Add(rbFemale);

            // 地址
            Panel addressPanel = new Panel { Width = 550, Height = 40 };
            Label lblAddress = new Label { Text = "地址:", Font = new Font("微软雅黑", 9), Location = new Point(10, 10), Width = 80 };
            txtAddress = new TextBox { Font = new Font("微软雅黑", 9), Location = new Point(100, 8), Width = 200, Height = 25 };
            addressPanel.Controls.Add(lblAddress);
            addressPanel.Controls.Add(txtAddress);

            // 联系电话
            Panel phonePanel = new Panel { Width = 550, Height = 40 };
            Label lblPhone = new Label { Text = "联系电话:", Font = new Font("微软雅黑", 9), Location = new Point(10, 10), Width = 80 };
            txtContactPhone = new TextBox { Font = new Font("微软雅黑", 9), Location = new Point(100, 8), Width = 200, Height = 25 };
            phonePanel.Controls.Add(lblPhone);
            phonePanel.Controls.Add(txtContactPhone);

            // 拼音缩写
            Panel pinyinPanel = new Panel { Width = 550, Height = 40 };
            Label lblPinyin = new Label { Text = "拼音缩写:", Font = new Font("微软雅黑", 9), Location = new Point(10, 10), Width = 80 };
            txtPinyinAbbreviation = new TextBox { Font = new Font("微软雅黑", 9), Location = new Point(100, 8), Width = 200, Height = 25 };
            pinyinPanel.Controls.Add(lblPinyin);
            pinyinPanel.Controls.Add(txtPinyinAbbreviation);

            // 类型
            Panel typePanel = new Panel { Width = 550, Height = 40 };
            Label lblType = new Label { Text = "类型:", Font = new Font("微软雅黑", 9), Location = new Point(10, 10), Width = 80 };
            cboType = new ComboBox { Font = new Font("微软雅黑", 9), Location = new Point(100, 8), Width = 200, Height = 25, DropDownStyle = ComboBoxStyle.DropDownList };
            cboType.Items.Add("请选择类型");
            cboType.Items.AddRange(new object[] { "医生", "护士", "管理员" ,"药房管理员" ,"收费员" });
            cboType.SelectedIndex = 0; // 选中"请选择类型"
            typePanel.Controls.Add(lblType);
            typePanel.Controls.Add(cboType);

            // 科室
            Panel departmentPanel = new Panel { Width = 550, Height = 40 };
            Label lblDepartment = new Label { Text = "科室:", Font = new Font("微软雅黑", 9), Location = new Point(10, 10), Width = 80 };
            cboDepartment = new ComboBox { Font = new Font("微软雅黑", 9), Location = new Point(100, 8), Width = 200, Height = 25, DropDownStyle = ComboBoxStyle.DropDownList };
            departmentPanel.Controls.Add(lblDepartment);
            departmentPanel.Controls.Add(cboDepartment);

            // 挂号费
            Panel feePanel = new Panel { Width = 550, Height = 40 };
            Label lblFee = new Label { Text = "挂号费:", Font = new Font("微软雅黑", 9), Location = new Point(10, 10), Width = 80 };
            txtRegistrationFee = new TextBox { Font = new Font("微软雅黑", 9), Location = new Point(100, 8), Width = 200, Height = 25, Text = "0.00" };
            feePanel.Controls.Add(lblFee);
            feePanel.Controls.Add(txtRegistrationFee);

            // 备注
            Panel remarkPanel = new Panel { Width = 550, Height = 80 };
            Label lblRemark = new Label { Text = "备注:", Font = new Font("微软雅黑", 9), Location = new Point(10, 10), Width = 80 };
            txtRemark = new TextBox { Font = new Font("微软雅黑", 9), Location = new Point(100, 8), Width = 300, Height = 60, Multiline = true };
            remarkPanel.Controls.Add(lblRemark);
            remarkPanel.Controls.Add(txtRemark);

            // 按钮面板
            Panel buttonPanel = new Panel { Width = 550, Height = 50 };
            btnSubmit = new Button
            {
                Text = "提交",
                Font = new Font("微软雅黑", 10, FontStyle.Bold),
                BackColor = Color.FromArgb(52, 152, 219),
                ForeColor = Color.White,
                Size = new Size(100, 35),
                Location = new Point(150, 8),
                FlatStyle = FlatStyle.Flat
            };
            btnSubmit.Click += BtnSubmit_Click;

            btnReset = new Button
            {
                Text = "重置",
                Font = new Font("微软雅黑", 10),
                BackColor = Color.FromArgb(149, 165, 166),
                ForeColor = Color.White,
                Size = new Size(100, 35),
                Location = new Point(270, 8),
                FlatStyle = FlatStyle.Flat
            };
            btnReset.Click += BtnReset_Click;

            buttonPanel.Controls.Add(btnSubmit);
            buttonPanel.Controls.Add(btnReset);

            // 添加所有面板到表单
            formPanel.Controls.Add(usernamePanel);
            formPanel.Controls.Add(passwordPanel);
            formPanel.Controls.Add(confirmPasswordPanel);
            formPanel.Controls.Add(realNamePanel);
            formPanel.Controls.Add(genderPanel);
            formPanel.Controls.Add(addressPanel);
            formPanel.Controls.Add(phonePanel);
            formPanel.Controls.Add(pinyinPanel);
            formPanel.Controls.Add(typePanel);
            formPanel.Controls.Add(departmentPanel);
            formPanel.Controls.Add(feePanel);
            formPanel.Controls.Add(remarkPanel);
            formPanel.Controls.Add(buttonPanel);

            // 组装界面
            mainPanel.Controls.Add(lblTitle);
            mainPanel.Controls.Add(formPanel);

            this.Controls.Add(mainPanel);

            // 动态加载科室数据
            LoadDepartments();
        }

        private async void BtnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证必填字段
                if (string.IsNullOrWhiteSpace(txtUsername.Text))
                {
                    MessageBox.Show("请输入用户名", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtUsername.Focus();
                    return;
                }

                if (string.IsNullOrWhiteSpace(txtRealName.Text))
                {
                    MessageBox.Show("请输入用户姓名", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtRealName.Focus();
                    return;
                }

                if (string.IsNullOrWhiteSpace(txtPassword.Text))
                {
                    MessageBox.Show("请输入用户密码", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtPassword.Focus();
                    return;
                }

                if (txtPassword.Text != txtConfirmPassword.Text)
                {
                    MessageBox.Show("两次输入的密码不一致", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtConfirmPassword.Focus();
                    return;
                }

                if (cboType.SelectedIndex == 0 || cboType.Text == "请选择类型")
                {
                    MessageBox.Show("请选择类型", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    cboType.Focus();
                    return;
                }

                // 构建请求数据
                var userData = new
                {
                    Username = txtUsername.Text.Trim(),
                    RealName = txtRealName.Text.Trim(),
                    UserPassword = txtPassword.Text,
                    Gender = rbMale.Checked ? 1 : 2, // 1-男, 2-女
                    Address = txtAddress.Text.Trim(),
                    ContactPhone = txtContactPhone.Text.Trim(),
                    PinyinAbbreviation = txtPinyinAbbreviation.Text.Trim(),
                    Type = GetTypeValue(cboType.Text), // 转换为整数
                    DepartmentId = GetDepartmentId(cboDepartment.Text), // 获取科室ID
                    RegistrationFee = decimal.TryParse(txtRegistrationFee.Text, out decimal fee) ? fee : 0.00m,
                    Remark = txtRemark.Text.Trim()
                };

                var json = JsonConvert.SerializeObject(userData);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await httpClient.PostAsync($"{apiBaseUrl}/api/User/create", content);
                var responseContent = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    var result = JsonConvert.DeserializeObject<ApiResult<int>>(responseContent);
                    if (result.Code == 200)
                    {
                        MessageBox.Show("用户添加成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        ResetForm();
                    }
                    else
                    {
                        MessageBox.Show($"添加失败: {result.Msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show($"请求失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnReset_Click(object sender, EventArgs e)
        {
            ResetForm();
        }

        private void ResetForm()
        {
            txtUsername.Text = "";
            txtRealName.Text = "";
            txtPassword.Text = "";
            txtConfirmPassword.Text = "";
            rbMale.Checked = true;
            txtAddress.Text = "";
            txtContactPhone.Text = "";
            txtPinyinAbbreviation.Text = "";
            cboType.SelectedIndex = 0; // 重置为"请选择类型"
            cboDepartment.SelectedIndex = 0;
            txtRegistrationFee.Text = "0.00";
            txtRemark.Text = "";
        }

        /// <summary>
        /// 科室名称到ID的映射字典
        /// </summary>
        private Dictionary<string, int> departmentIdMapping = new Dictionary<string, int>();

        private async void LoadDepartments()
        {
            try
            {
                cboDepartment.Items.Clear();
                cboDepartment.Items.Add("请选择科室");
                cboDepartment.SelectedIndex = 0;
                departmentIdMapping.Clear();

                // 使用新的一级科室API接口
                var apiUrl = "http://101.201.170.32:5115/api/ContentManagement/Department/GetFirstLevelDepartments";
                
                var response = await httpClient.GetAsync(apiUrl);
                
                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    
                    var result = JsonConvert.DeserializeObject<FirstLevelDepartmentResponseDto>(content);
                    if (result.Code == 200 && result.PageData != null && result.PageData.Count > 0)
                    {
                        cboDepartment.Items.Clear();
                        cboDepartment.Items.Add("请选择科室");
                        
                        // 添加所有科室到下拉框
                        foreach (var dept in result.PageData)
                        {
                            cboDepartment.Items.Add(dept.DepartmentName);
                            // 建立科室名称到ID的映射
                            departmentIdMapping[dept.DepartmentName] = dept.Id;
                        }
                        cboDepartment.SelectedIndex = 0;
                    }
                    else
                    {
                        LoadDefaultDepartments();
                    }
                }
                else
                {
                    LoadDefaultDepartments();
                }
            }
            catch (Exception ex)
            {
                LoadDefaultDepartments();
            }
        }



        private void LoadDefaultDepartments()
        {
            cboDepartment.Items.Clear();
            cboDepartment.Items.Add("请选择科室");
            cboDepartment.Items.Add("内科");
            cboDepartment.Items.Add("外科");
            cboDepartment.Items.Add("儿科");
            cboDepartment.SelectedIndex = 0;
            
            // 为默认科室建立映射
            departmentIdMapping.Clear();
            departmentIdMapping["内科"] = 1;
            departmentIdMapping["外科"] = 2;
            departmentIdMapping["儿科"] = 3;
        }

        /// <summary>
        /// 获取类型值
        /// </summary>
        /// <param name="typeText">类型文本</param>
        /// <returns>类型值</returns>
        private int GetTypeValue(string typeText)
        {
            switch (typeText)
            {
                case "医生":
                    return 1;
                case "护士":
                    return 2;
                case "管理员":
                    return 3;
                case "药房管理员":
                    return 4;
                case "收费员":
                    return 5;
                case "请选择类型":
                default:
                    return 0; // 未选择类型
            }
        }

        /// <summary>
        /// 获取科室ID
        /// </summary>
        /// <param name="departmentText">科室文本</param>
        /// <returns>科室ID</returns>
        private int? GetDepartmentId(string departmentText)
        {
            if (string.IsNullOrEmpty(departmentText) || departmentText == "请选择科室")
            {
                return null;
            }

            // 从映射字典中获取科室ID
            if (departmentIdMapping.TryGetValue(departmentText, out int departmentId))
            {
                return departmentId;
            }

            // 如果映射中没有找到，返回null
            return null;
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private System.ComponentModel.IContainer components = null;
    }
} 